/*	$Id: dlink_bpf.c 7 2008-07-29 02:58:11Z phrakt $	*/
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <jfb@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Berkeley Packet Filter specific code
 *
 * This file contains all the code required to use the BPF interface found on
 * most *BSD systems as the datalink layer underneath.
 */


#include <sys/types.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/socket.h>

#include <net/if.h>
#include <net/bpf.h>

#include <poll.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include "if.h"
#include "pkt.h"
#include "dlink.h"
#include "pforge.h"

#define BPF_MAXPATHLEN  16


int            dlink_bpf_open  (PF_DLINK *);
int            dlink_bpf_close (PF_DLINK *);
int            dlink_bpf_bind  (PF_DLINK *, int);
int            dlink_bpf_ctl   (PF_DLINK *, int, void *);
pfnet_pkt_t*   dlink_bpf_read  (PF_DLINK *);
ssize_t        dlink_bpf_write (PF_DLINK *, void *, size_t);

static int dlink_bpf_pfex2prog (const PF_EXPR *, struct bpf_program *);

struct pf_dlink_ops dlink_bpf_ops = {
	dlink_bpf_open,
	dlink_bpf_close,
	dlink_bpf_bind,
	dlink_bpf_ctl,
	dlink_bpf_read,
	dlink_bpf_write
};


/*
 * dlink_bpf_open()
 *
 * Open a Berkeley Packet Filter device and return an abstract structure
 * representing the device.
 * Returns -1 on failure.
 */
int
dlink_bpf_open(PF_DLINK *dl)
{
	int hdrcmp, imm;
	int bpf_id, bpf_fd;
	char bpf_dev[BPF_MAXPATHLEN];
	struct bpf_version version;

	for (bpf_id = 0; ; bpf_id++) {
		snprintf(bpf_dev, sizeof(bpf_dev), "/dev/bpf%d", bpf_id);
		bpf_fd = open(bpf_dev, O_RDWR);
		if (bpf_fd == -1) {
			if (errno == ENOENT) {
				/* there's no hope */
				return (-1);
			}
			if (errno == EBUSY)
				continue;

		}
		else
			break;
	}

	/* first check if we have the right version */
	if (ioctl(bpf_fd, BIOCVERSION, &version) < 0) {
		return (-1);
	}

	if ((version.bv_major != BPF_MAJOR_VERSION) ||
	    (version.bv_minor < BPF_MINOR_VERSION)) {
		(void)close(bpf_fd);
		return (-1);
	}

#if defined(__OpenBSD__)
	/*
	* Tell BPF that we will be providing our own link-layer headers on the
	* packets.
	*/
	hdrcmp = 1;
	if (ioctl(bpf_fd, BIOCSHDRCMPLT, &hdrcmp) < 0) {
		(void)close(bpf_fd);
		return (-1);
	}
#endif

	if (ioctl(bpf_fd, BIOCSRTIMEOUT, &(dl->timeout)) < 0) {
		return (-1);
	}

	/* we want to receive packets immediately */
	imm = 1;
	if (ioctl(bpf_fd, BIOCIMMEDIATE, &imm) < 0) {
		return (-1);
	}

	strlcpy(dl->dldev, bpf_dev, sizeof(dl->dldev));

	printf("BPF version %u.%u\n",
	    version.bv_major, version.bv_minor);

	dl->dlfd = bpf_fd;

	return (bpf_fd);
}


/*
 * dlink_bpf_close()
 *
 * Close the BPF interface descriptor.
 */
int
dlink_bpf_close(PF_DLINK *dl)
{
	if (dl == NULL)
		return (-1);
	(void)close(dl->dlfd);

	return 0;
}


/*
 * dlink_bpf_bind()
 *
 * Bind the dlink layer structure <dl> to the network interface <ifp>.
 * In order to make sure that reads from the BPF device will not return
 * truncated packets, we set the capture length to <ifp>'s MTU.
 */
int
dlink_bpf_bind(PF_DLINK *dl, int nid)
{
	int blen;
	void *buf;
	struct pf_netif_info ifinfo;
	struct ifreq ifr;

	if (pf_netif_getinfo(nid, &ifinfo) < 0)
		return (-1);

	blen = ifinfo.ifi_mtu + sizeof(struct bpf_hdr);
	if (ioctl(dl->dlfd, BIOCSBLEN, &blen) < 0) {
		return (-1);
	}

	strlcpy(ifr.ifr_name, ifinfo.ifi_name, sizeof(ifr.ifr_name));
	if (ioctl(dl->dlfd, BIOCSETIF, &ifr) < 0) {
		return (-1);
	}

	/*
	 * Reallocate the read buffer to match the MTU + the size of the
	 * BPF header which gets prepended to every received packet
	 */
	buf = realloc(dl->rbuf, blen);
	if (buf == NULL) {
		pf_seterr(PF_ERR_NOMEM);
		return (-1);
	}

	dl->rbuf = buf;
	dl->rbufsz = blen;

	return (0);
}

/*
 * dlink_bpf_ctl()
 *
 * BPF-dependent version of the control function for datalink layer.
 */
int
dlink_bpf_ctl(PF_DLINK *dl, int type, void *data)
{
	int ret;
	struct timeval *tv;
	struct bpf_program bpf_prog;
	struct bpf_stat bpf_st;
	struct pfdlink_stats *dlsp;
	PF_EXPR *expr;

	switch (type) {
	case PFDL_CTL_SPROMISC:
		ret = ioctl(dl->dlfd, BIOCPROMISC);
		if (ret == -1) {
		}
		break;

	case PFDL_CTL_SRTIMEOUT:
		tv = (struct timeval *)data;
		ret = ioctl(dl->dlfd, BIOCSRTIMEOUT, tv);
		if (ret >= 0) {
			dl->timeout.tv_sec = tv->tv_sec;
			dl->timeout.tv_usec = tv->tv_usec;
		}
		break;
	case PFDL_CTL_GSTATS:
		dlsp = data;
		ret = ioctl(dl->dlfd, BIOCGSTATS, &bpf_st);
		if (ret < 0) {
			return (-1);
		}
		break;
	case PFDL_CTL_SFLTR:
		expr = (PF_EXPR *)data;
		dlink_bpf_pfex2prog(data, &bpf_prog);
		ret = ioctl(dl->dlfd, BIOCSETF, &bpf_prog);
		if (bpf_prog.bf_insns != NULL)
			free(bpf_prog.bf_insns);
		break;
	case PFDL_CTL_GFLTR:
		pf_seterr(PF_ERR_NOTSUP);
		ret = -1;
		break;
	default:
		ret = -1;
		break;
	}

	return (ret);
}


/*
 * dlink_bpf_read()
 *
 * Read bytes from the BPF device.
 * Returns the number of bytes contained in the captured packet on success,
 * or -1 on failure.
 */
pfnet_pkt_t*
dlink_bpf_read(PF_DLINK *dl)
{
	ssize_t bytes;
	uint8_t *dp;
	struct bpf_hdr *hdr;
	pfnet_pkt_t *pkt;

	bytes = read(dl->dlfd, dl->rbuf, dl->rbufsz);
	if (bytes == -1) {
		return (NULL);
	} else if (bytes == 0) {
		return (NULL);
	}

	dp = dl->rbuf;
	hdr = (struct bpf_hdr *)dp;
	dp += hdr->bh_hdrlen;

	pkt = pf_pkt_alloc();

	pkt->pkt_ts.tv_sec = hdr->bh_tstamp.tv_sec;
	pkt->pkt_ts.tv_nsec = hdr->bh_tstamp.tv_usec * 1000;
	pkt->pkt_len = hdr->bh_caplen;

	pf_pkt_set(pkt, dp, (size_t)bytes);

	dl->dl_stats.dl_inbytes += hdr->bh_caplen;
	dl->dl_stats.dl_inpkt++;

	return (pkt);
}


/*
 * dlink_bpf_write()
 *
 * Write a packet to the datalink layer.
 *
 * Returns the number of bytes written to the device on success, or -1 on
 * failure.
 */
ssize_t
dlink_bpf_write(PF_DLINK *dl, void *src, size_t len)
{
	ssize_t sbytes;

	sbytes = 0;

	dl->dl_stats.dl_outpkt++;

	return (sbytes);
}


/*
 * dlink_bpf_pfex2prog()
 *
 * Translate a Packet Forge packet expression into the BPF equivalent.
 */
static int
dlink_bpf_pfex2prog(const PF_EXPR *expr, struct bpf_program *prog)
{
	/* XXX implement! */
	prog->bf_len = 0;
	prog->bf_insns = NULL;
	return (0);
}
